const fs = require('fs');
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const { insertIntoDB } = require('./mysql.js');

const nameBuffer = fs.readFileSync('./百家姓.txt');
const names = nameBuffer.toString();
const files = fs.readdirSync('./msgs');

setTimeout(() => {
  startJob();
}, 1000);

function handleJoinedDiv(divDom, onFinish) {
  if (divDom.querySelector('.text').querySelector('a')) {
    divDom.querySelector('.text').querySelector('a').innerHTML = '';
  }

  const text = divDom.querySelector('.text').textContent.trim();
  const groupsInfo = text.split('QQ');
  const lastIdx = groupsInfo.length - 1;
  const len = lastIdx + 1;
  if (len === 0) onFinish();
  let count = 0;
  function canResolve2() {
    count++;
    if (count === len) {
      onFinish();
    }
  }
  groupsInfo.forEach((info, index) => {
    if (info.includes('昵称')) {
      let name = info.match(/昵称:([\u4e00-\u9fa5].*)年龄/)?.[1];
      if(name){
        name = name.trim()
      }
      if (name && names.indexOf(name[0]) !== -1) {
        const qq = info.match(/[0-9]+/)[0];
        insertIntoDB(qq, name, canResolve2);
      } else {
        canResolve2();
      }
    } else {
      canResolve2();
    }
  });
}

async function startJob() {
  for (let i = 0; i < files.length; i++) {
    console.log('文件总数：', files.length, ' 当前处理: ', i + 1);
    await wrapTask(files[i]);
    console.log(`${files[i]}文件处理完毕，按 Ctrl+C 退出程序。`);
  }
}

function wrapTask(filename) {
  return new Promise((resolve) => {
    const strBuffer = fs.readFileSync(`./msgs/${filename}`);
    const htmlText = strBuffer.toString();
    const dom = new JSDOM(htmlText);
    const joinedDivs = dom.window.document.body.querySelectorAll(
      '.message.default.clearfix.joined'
    );
    let count = 0;
    let total = joinedDivs.length;
    if (total === 0) {
      resolve();
    }
    function canResolve() {
      count++;
      if (count === total) resolve();
    }
    joinedDivs.forEach((item) => handleJoinedDiv(item, canResolve));
  });
}
